package com.huike.web.controller.contract;

import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.vo.TransferListVo;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessService;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.service.ITbAssignRecordService;
import com.huike.clues.service.ITbClueService;
import com.huike.common.annotation.Log;
import com.huike.common.core.controller.BaseController;
import com.huike.common.core.domain.AjaxResult;
import com.huike.common.core.domain.entity.SysUser;
import com.huike.common.core.page.TableDataInfo;
import com.huike.common.enums.BusinessType;
import com.huike.common.utils.StringUtils;
import com.huike.contract.domain.vo.TransferVo;
import com.huike.contract.service.ITransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/transfer")
public class TransferController extends BaseController {
    @Autowired
    private ITbBusinessService tbBusinessService;
    @Autowired
    private ITbClueService tbClueService;
    @Autowired
    private ITbAssignRecordService itbAssignRecordService;
    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;


    /**
     * 查询转派管理列表
     * @param
     * @return
     */
    @PreAuthorize("@ss.hasPermi('transfer:transfer:list')")
    @GetMapping("/list")
    public TableDataInfo list(TransferListVo tbBusiness, HttpServletRequest req){
        String parameterBeg = req.getParameter("params[beginCreateTime]");
        String parameterEnd = req.getParameter("params[endCreateTime]");
        if((!StringUtils.isEmpty(parameterBeg))&&
                (!StringUtils.isEmpty(parameterEnd))) {
            tbBusiness.setBeginCreateTime(parameterBeg);
            tbBusiness.setEndCreateTime(parameterEnd);
        }
        //根据 条件查询 用户信息  获取到id 用户名  手机号码
        ArrayList<TransferListVo> transferListVos=tbBusinessService.getTransferUser(tbBusiness);

        for (int i = 0; i < transferListVos.size(); i++) {
            TransferListVo transferListVo = transferListVos.get(i);
            //根据用户名获取到 线索的条数 商机的条数 创建消息时间
            HashMap<String,Object> clueNums = tbClueService.selectTbClueByUserName(transferListVo.getUserName());
            Long clueNum = (Long) clueNums.get("clueNum");
            Long businessNum = (Long) clueNums.get("businessNum");
            Date createTime = (Date) clueNums.get("createTime");
            transferListVo.setClueNum(clueNum);
            transferListVo.setBusinessNum(businessNum);
            transferListVo.setCreateTime(createTime);
            if (clueNum ==0 && businessNum == 0) {
                transferListVos.remove(i);
                i--;
            }
        }
        BaseController baseController = new BaseController();
        return baseController.getDataTablePage(transferListVos);
    }

    @Transactional
    @PutMapping("/assignment/{type}/{userId}/{transferUserId}")
    public AjaxResult assignment(@PathVariable String type ,@PathVariable Long userId ,@PathVariable Long transferUserId){
        //先判断类型是 线索 typ=0
        //查询 根据传出的userId获取到对应的线索或者商机id  根据转入用户userId 查询sys_user查询出名字(子查询) 部门id(子查询) 获取到状态     当前时间   分配人
        //线索
         ArrayList<TbAssignRecord> tbAssignRecord= itbAssignRecordService.selectAssignRecordByUserId(type,userId);
            for (TbAssignRecord assignRecord : tbAssignRecord) {
                //添加 到线索商机 跟进表中
                assignRecord.setUserId(transferUserId);
                assignRecord.setType(type);
                assignRecord.setLatest("1");
                //获取到部门id  获取到传入的用户名字
               HashMap<String,Object> map= itbAssignRecordService.getDeptIdName(transferUserId);
                Long deptId = (Long) map.get("deptId");
                String userName = (String) map.get("userName");
                assignRecord.setDeptId(deptId);
                assignRecord.setUserName(userName);
                //添加数据到 线索商机跟进表
                int i = itbAssignRecordService.insertAssignRecord(assignRecord);
                //获取到用户线索或者 商机的id
                //修改线索商机跟进表的数据  为不是最新跟进人
                TbAssignRecord latest = new TbAssignRecord();
                latest.setLatest("0");
                latest.setId(assignRecord.getId());
                itbAssignRecordService.updateTbClueAssignRecord(latest);
                if(type =="0"){//修改线索表
                    TbClue tbClue = new TbClue();
                    tbClue.setId(assignRecord.getAssignId());//根据id修改
                    tbClue.setCreateBy(userName);//修改创建人
                    tbClue.setUpdateTime(new Date());//修改修改时间
                    tbClueService.updateTbClue( tbClue);
                }else {
                    //修改商机表
                    TbBusiness tbBusiness = new TbBusiness();
                    tbBusiness.setId(assignRecord.getAssignId());//根据id修改
                    tbBusiness.setCreateBy(userName);//修改创建人
                    tbBusiness.setUpdateTime(new Date());//修改修改时间
                    tbBusinessService.updateTbBusiness(tbBusiness);

                }

            }

        return AjaxResult.success("转派成功");
    }
}